import React, {Component} from 'react'
import './index.scss'

class ToTop extends Component {
		constructor(props) {
				super(props);
				this.state = {
						isShow: false
				}
		}

		render() {
				return (
						<div id="toTop">
								{
										this.state.isShow ?
												<div className="container" onClick={this.toTop.bind(this)}>
														<span className="iconfont icon-top"/>
												</div>
										:null
								}
						</div>
				)
		}
		componentDidMount() {
				document.onscroll = this.handleScroll.bind(this)
		}

		handleScroll() {
				let scrollTop = document.documentElement.scrollTop ?
						document.documentElement.scrollTop :
						document.body.scrollTop;
				if (scrollTop >= 1200) {
						this.setState({
								isShow: true
						})
				} else {
						this.setState({
								isShow: false
						})
				}
		}

		toTop() {
				let scrollTop = document.documentElement.scrollTop ?
						document.documentElement.scrollTop :
						document.body.scrollTop;

				let speed = scrollTop / 20;
				let id = setInterval(function () {
						document.documentElement.scrollTop -= speed;
						document.body.scrollTop -= speed;
						let scrollTop = document.documentElement.scrollTop ?
								document.documentElement.scrollTop :
								document.body.scrollTop;
						if (0 === scrollTop) {
								clearInterval(id);
						}
				}, 20)
		}

}

export default ToTop
